﻿#pragma execution_character_set("utf-8")

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置进度条
    ui->progressBar->setValue(0);
    ui->progressBar->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    ui->progressBar->setFormat(QString::fromUtf8("当前无任务：%1%").arg(QString::number(0, 'f', 1)));
}

Widget::~Widget()
{
    delete ui;
}

// 初始化记录URL地址，用户名，密码，并检测URL地址的合法性
bool Widget::initFTP()
{
    // 判断有没有填写URL地址和用户名、密码
    if (ui->lineEdit_addr->text().isEmpty())
    {
        QMessageBox::critical(NULL, tr("Error"), "URL地址不能为空");
        return false;
    }
    else if (ui->lineEdit_UserName->text().isEmpty())
    {
        QMessageBox::critical(NULL, tr("Error"), "user不能为空");
        return false;
    }
    else if (ui->lineEdit_Password->text().isEmpty())
    {
        QMessageBox::critical(NULL, tr("Error"), "密码不能为空");
        return false;
    }
    else
    {
        m_FtpPath = ui->lineEdit_addr->text();
        m_User = ui->lineEdit_UserName->text();
        m_Password = ui->lineEdit_Password->text();

        // 检测URL地址是否合法
        QUrl url = QUrl(m_FtpPath);
        if (!url.isValid())
        {
            QMessageBox::critical(NULL, tr("Error"), "URL地址不合法！");
            return false;
        }
        else if (url.scheme() != "ftp")
        {
            QMessageBox::critical(NULL, tr("Error"), "URL地址必须以ftp开头！");
            return false;
        }

        return true;
    }
}

// 删除指针，更新和关闭文件
void Widget::replyFinished(QNetworkReply*)
{
    if (m_reply->error() == QNetworkReply::NoError)
    {
        m_reply->deleteLater();
        m_file->flush();
        m_file->close();
    }
    else
    {
        QMessageBox::critical(NULL, tr("Error"), "错误!!!");
    }
}

// 更新进度条
void Widget::loadProgress(qint64 bytesSent, qint64 bytesTotal)
{
    ui->progressBar->setValue(0);
    qDebug() << "loaded" << bytesSent << "of" << bytesTotal;
    ui->progressBar->setMaximum(bytesTotal); //最大值
    ui->progressBar->setValue(bytesSent);  //当前值
    double currentProgress = (bytesSent - ui->progressBar->minimum()) * 100.0 / (bytesTotal - ui->progressBar->minimum());
    ui->progressBar->setFormat(QString::fromUtf8("当前进度为：%1%").arg(QString::number(currentProgress, 'f', 1)));
}

// 获得传入路径的文件名
QString Widget::getFileName(QString m_filePath)
{
    QString temp;
    QString fileName;
    int count = -1;
    fileName = m_filePath;
    for(int i = 0; temp != "/"; i++)
    {
        temp = fileName.right(1);
        fileName.chop(1);
        count++;
    }
    fileName = m_filePath.right(count);

    return fileName;
}

// 下载过程出错，进行报错处理（超时处理也是丢出超时信号，交由此槽函数进行处理）
void Widget::replyError(QNetworkReply::NetworkError error)
{
    auto metaEnum = QMetaEnum::fromType<QNetworkReply::NetworkError>();
    // 枚举值转换为字符串
    auto errStr = metaEnum.valueToKey(error);
    QMessageBox::critical(NULL, tr("Error"), QString(errStr));

    m_file->deleteLater();
    m_file = Q_NULLPTR;

    m_reply->deleteLater();
}

// 下载时向本地文件中写入数据
void Widget::readContent()
{
    m_file->write(m_reply->readAll());
}

// 上传文件
void Widget::on_btnUp_clicked()
{
    if (initFTP())
    {
        // 得到选择的文件的路径，保存在字符串链表中
        QStringList string_list;

        //可以选择多个文件同时上传
        string_list = QFileDialog::getOpenFileNames(this, tr("选择文件"), "", tr("Files (*)"));
        if (!string_list.isEmpty())
        {
            for (int i = 0; i < string_list.count(); i++)
            {
                QString filePath;
                filePath = string_list.at(i);  //获取单个上传文件的名字

                m_file = new QFile(filePath);
                m_file->open(QIODevice::ReadOnly);
                QByteArray byte_file = m_file->readAll();

                QString fileName;
                fileName = getFileName(filePath);
                QString _ftpPath;
                _ftpPath = m_FtpPath + "/" + fileName;

                // 把选中的文件上传到服务器
                m_AccessManager = new QNetworkAccessManager(this);
                m_AccessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
                QUrl url(_ftpPath);
                url.setPort(21);
                url.setUserName(m_User);
                url.setPassword(m_Password);

                QNetworkRequest request(url);
                m_reply = m_AccessManager->put(request, byte_file);

                connect(m_AccessManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
                connect(m_reply, SIGNAL(uploadProgress(qint64 ,qint64)), this, SLOT(loadProgress(qint64 ,qint64)));
                connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),SLOT(replyError(QNetworkReply::NetworkError)));
            }
        }
    }
}

// 下载文件
void Widget::on_btnDown_clicked()
{
    if (initFTP())
    {
        QString folderPath;
        folderPath = QFileDialog::getExistingDirectory(this, tr("选择文件"), "", QFileDialog::ShowDirsOnly);
        m_file = new QFile(folderPath + "1000.jpg");  //下载后的文件名
        m_file->open(QIODevice::WriteOnly);

        // 从服务器上下载文件到选中文件夹
        QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
        accessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
        QUrl url("ftp://127.0.0.1/4.jpg");  //ftp服务器的文件名
        url.setPort(21);
        url.setUserName("qwer");
        url.setPassword("1234");

        QNetworkRequest request(url);
        m_reply = accessManager->get(request);

        connect((QObject *)m_reply, SIGNAL(readyRead()), this, SLOT(readContent()));
        connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
        connect(m_reply, SIGNAL(downloadProgress(qint64 ,qint64)), this, SLOT(loadProgress(qint64 ,qint64)));
        connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),SLOT(replyError(QNetworkReply::NetworkError)));
    }
}

